-- Function: insertar_diagnosticoxfis50ms(character varying, character varying, character varying, character varying)

-- DROP FUNCTION insertar_diagnosticoxfis50ms(character varying, character varying, character varying, character varying);

CREATE OR REPLACE FUNCTION insertar_diagnosticoxfis50ms(IN v_idconsulta character varying, IN v_idcaracteristica character varying, IN v_calificacion character varying, IN v_evaluacion_paciente_id character varying, OUT v_result character varying)
  RETURNS character varying AS
$BODY$
BEGIN

--Insertar caracteristicas en fuerza y saltabilidad      
 INSERT INTO diagnosticoxfis50ms
    (
    calificacion,
    created, 
    updated,    
    consulta_id, 
    caracteristica_id,
    evaluacion_paciente_id 
    
    
    )
    VALUES 
    (
    v_calificacion,
    NOW(),
    NOW(),  
    v_idConsulta::integer,
    v_idCaracteristica::integer,
    v_evaluacion_paciente_id::integer
    );

    EXCEPTION

            WHEN unique_violation THEN
        --Actualizar caracteristicas en fuerza y saltabilidad         
        UPDATE  diagnosticos
        SET
        calificacion = v_calificacion
        WHERE
        consulta_id = v_idConsulta and
        caracteristica_id = v_idCaracteristica; 
            v_result:= 1;
            RETURN;

            WHEN foreign_key_violation THEN
            v_result:= 2;
        RETURN;
 
            WHEN not_null_violation THEN
            v_result:= 3;
        RETURN;

--FALTA CAPTURAR OTHER EXCEPTION

      


END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION insertar_diagnosticoxfis50ms(character varying, character varying, character varying, character varying)
  OWNER TO postgres;
